﻿//////////////////////////////////////////////////////////////////////////////
//
//  Copyright © 1998-2024 Glodon Company Limited.  All rights reserved.
//
//  Use of this software is subject to the terms of the Glodon license
//  agreement provided at the time of installation or download, or which
//  otherwise accompanies this software in either electronic or hard copy form.  
//
//////////////////////////////////////////////////////////////////////////////


#pragma once

namespace gcmp {
    
    template <class TState>
    class StateGuard final
    {
    public:
        StateGuard(TState _initial_, TState _default_)
            : m_current(_initial_)
            , m_default(_default_)
            , m_pending(_default_) {}

        TState operator()() const { return m_current; }
        TState pending()    const { return m_pending; }

        bool isSwitching() const { return (m_default != m_pending); }

        bool startSwitchingTo(TState state)
        {
            DBG_WARN_AND_RETURN_FALSE_UNLESS(!isSwitching(), L"Switching!", L"GMEP", L"2022-11-28");
            
            m_pending = state;
            return isSwitching();
        }

        void finishSwitching()
        {
            if (!isSwitching())
                return;
            
            m_current = m_pending; //   set the current
            m_pending = m_default; // reset the pending
        }

    private:
        TState m_current;
        const TState m_default;
        TState m_pending;
    };
}